<template>
  <div class="data-table">
    <!-- 搜索栏 -->
    <div v-if="showSearch" class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item
          v-for="field in searchFields"
          :key="field.prop"
          :label="field.label"
        >
          <el-input
            v-if="field.type === 'input'"
            v-model="searchForm[field.prop]"
            :placeholder="`请输入${field.label}`"
            clearable
            style="width: 200px"
          />
          <el-select
            v-else-if="field.type === 'select'"
            v-model="searchForm[field.prop]"
            :placeholder="`请选择${field.label}`"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="option in field.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-date-picker
            v-else-if="field.type === 'date'"
            v-model="searchForm[field.prop]"
            type="date"
            :placeholder="`请选择${field.label}`"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作栏 -->
    <div v-if="showActions" class="action-bar">
      <div class="action-left">
        <slot name="actions">
          <el-button type="primary" @click="$emit('add')">
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="$emit('batchDelete', selectedRows)"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </slot>
      </div>
      <div class="action-right">
        <el-button-group>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
          </el-button>
          <el-button @click="showColumnSettings = true">
            <el-icon><Setting /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      ref="tableRef"
      :data="data"
      :loading="loading"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      v-bind="$attrs"
    >
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        v-if="showIndex"
        type="index"
        label="序号"
        width="80"
        align="center"
      />

      <el-table-column
        v-for="column in visibleColumns"
        :key="column.prop"
        v-bind="column"
      >
        <template v-if="column.slot" #default="scope">
          <slot :name="column.slot" v-bind="scope" />
        </template>
      </el-table-column>

      <el-table-column
        v-if="showActions"
        label="操作"
        :width="actionWidth"
        align="center"
        fixed="right"
      >
        <template #default="scope">
          <slot name="row-actions" v-bind="scope">
            <el-button type="primary" link @click="$emit('edit', scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="$emit('delete', scope.row)">
              删除
            </el-button>
          </slot>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div v-if="showPagination" class="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="pageSizes"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 列设置对话框 -->
    <el-dialog
      v-model="showColumnSettings"
      title="列设置"
      width="400px"
    >
      <el-checkbox-group v-model="selectedColumns">
        <div v-for="column in columns" :key="column.prop" class="column-item">
          <el-checkbox :label="column.prop">{{ column.label }}</el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="showColumnSettings = false">取消</el-button>
        <el-button type="primary" @click="handleColumnSettingsConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  align?: 'left' | 'center' | 'right'
  sortable?: boolean | 'custom'
  slot?: string
  [key: string]: any
}

export interface SearchField {
  prop: string
  label: string
  type: 'input' | 'select' | 'date'
  options?: Array<{ label: string; value: any }>
}

interface Props {
  data: any[]
  columns: TableColumn[]
  loading?: boolean
  showSearch?: boolean
  showActions?: boolean
  showSelection?: boolean
  showIndex?: boolean
  showPagination?: boolean
  searchFields?: SearchField[]
  total?: number
  pageSize?: number
  currentPage?: number
  pageSizes?: number[]
  actionWidth?: string | number
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  showSearch: true,
  showActions: true,
  showSelection: true,
  showIndex: true,
  showPagination: true,
  searchFields: () => [],
  total: 0,
  pageSize: 20,
  currentPage: 1,
  pageSizes: () => [10, 20, 50, 100],
  actionWidth: 150
})

const emit = defineEmits<{
  add: []
  edit: [row: any]
  delete: [row: any]
  batchDelete: [rows: any[]]
  search: [params: any]
  refresh: []
  sizeChange: [size: number]
  currentChange: [page: number]
  sortChange: [sort: { prop: string; order: string }]
}>()

const tableRef = ref()
const selectedRows = ref<any[]>([])
const searchForm = ref<Record<string, any>>({})
const showColumnSettings = ref(false)
const selectedColumns = ref<string[]>([])

// 可见列
const visibleColumns = computed(() => {
  return props.columns.filter(column => selectedColumns.value.includes(column.prop))
})

// 初始化搜索表单
const initSearchForm = () => {
  const form: Record<string, any> = {}
  props.searchFields.forEach(field => {
    form[field.prop] = ''
  })
  searchForm.value = form
}

// 初始化列选择
const initColumnSelection = () => {
  selectedColumns.value = props.columns.map(column => column.prop)
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 处理搜索
const handleSearch = () => {
  emit('search', { ...searchForm.value })
}

// 处理重置
const handleReset = () => {
  initSearchForm()
  emit('search', {})
}

// 处理刷新
const handleRefresh = () => {
  emit('refresh')
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  emit('sizeChange', size)
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  emit('currentChange', page)
}

// 处理排序变化
const handleSortChange = (sort: { prop: string; order: string }) => {
  emit('sortChange', sort)
}

// 处理列设置确认
const handleColumnSettingsConfirm = () => {
  showColumnSettings.value = false
}

onMounted(() => {
  initSearchForm()
  initColumnSelection()
})
</script>

<style lang="scss" scoped>
.data-table {
  .search-bar {
    background: #fff;
    padding: 16px;
    margin-bottom: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .action-left {
      .el-button + .el-button {
        margin-left: 8px;
      }
    }
  }

  .pagination {
    margin-top: 16px;
    text-align: right;
  }

  .column-item {
    margin-bottom: 8px;
  }
}
</style>
